import {ActivatedRouteSnapshot, CanDeactivate, RouterStateSnapshot} from "@angular/router";
import {BaseComponent} from '../../components/base-component/base-component';
import {MessageService} from "./message-service";
import {Logger} from '../../utils';
import {Injectable} from "@angular/core";
import {Observable} from "rxjs";

@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<BaseComponent> {
    constructor(private messageService: MessageService) {
    }

    canDeactivate(target: BaseComponent,
                  currentRoute: ActivatedRouteSnapshot,
                  currentState: RouterStateSnapshot,
                  nextState?: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        Logger.log("ConfirmDeactivateGuard: " + target.hasChanges());
        if (target.hasChanges()) {
            return new Promise((resolve, reject) => {
                this.messageService.confirm("Shared.message.unsavedDataConfirmation",
                    "Shared.ok","Shared.no", (result) => {
                        resolve(result);
                    });
            });
        } else {
            return true;
        }
    }
}
